package com.aiti.lulian.components.wx;

import com.aiti.lulian.components.wx.domain.TokenResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 获取Token的组件
 * <p>
 *     你可以将这个组件理解中一个<br />
 *     服务于微信Token的中控服务器，这个类只需负责Token的刷新及获取
 *     这个类中必须要保证当前的Token是一个可用的Token
 * </p>
 */
@Component
@ConditionalOnProperty(name = "wx.token-switch", havingValue = "true", matchIfMissing = false)
public class AccessTokenComponents {

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Value("${wx.token}")
    private String token;

    private StringRedisTemplate redisTemplate;

    private RestTemplate restTemplate;

    private final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    private final String WX_TOKEN_REDIS_KEY = "wx:token";

    public AccessTokenComponents(StringRedisTemplate redisTemplate,RestTemplate restTemplate) {
        this.redisTemplate = redisTemplate;
        this.restTemplate = restTemplate;
    }

    /**
     * 获取AccessToken方法
     * @return
     */
    @Scheduled(fixedRate = 110 * 60 * 1000)
    public void getAccessToken(){
        String finalUsl = String.format(GET_TOKEN_URL,appId,appSecret);
        ResponseEntity<TokenResponse> responseEntity = restTemplate.getForEntity(finalUsl, TokenResponse.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            TokenResponse body = responseEntity.getBody();
            redisTemplate.opsForValue().set(WX_TOKEN_REDIS_KEY,body.getAccessToken(),7200, TimeUnit.SECONDS);
        }else{
            throw new RuntimeException("获取微信Token失败，所有服务号推送功能不可用");
        }
    }
}
